package com.kangwd.utils;

import java.io.*;
import java.net.ConnectException;
import java.util.Properties;
import java.util.regex.Pattern;

import com.alibaba.druid.sql.visitor.functions.If;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.springframework.util.StringUtils;


/**
 * word格式转换
 * @author kangwd
 * @date 2019-01-15
 */
public class DocConvertUtil {
    private static int ENVIRONMENT ; // 环境 1：Windows 2：Linux 默认1
    private static String swftoolsPath;
    private String fileString;// (只涉及PDF2swf路径问题)
    private String outputPath = "";// 输入路径 ，如果不设置就输出在默认 的位置
    private String fileName;
    private File pdfFile;
    private File swfFile;
    private File docFile;
    static {
        //读取配置文件
        InputStream in = DocConvertUtil.class.getClassLoader().getResourceAsStream("preview.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            swftoolsPath = p.getProperty("swftool_path");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //根据项目所在的服务器环境
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Linux.*", osName)) {
            ENVIRONMENT = 2;
        } else if(Pattern.matches("Windows.*", osName)) {
            ENVIRONMENT = 1;
        } else {
            ENVIRONMENT = 1;
        }
    }
    public DocConvertUtil(String fileString) {
    }

    /**
     *  转为PDF
     *  转换成功返回pdf访问路径
     *
     */
    public static String doc2pdf(String fileName) throws Exception {
        if (StringUtils.isEmpty(fileName)) {
            throw new Exception("openoffice转换异常:源文件为空!");
        }
        String target = fileName;
        target = target.substring(0, target.lastIndexOf("."));
        File docFile = new File(fileName);
        File pdfFile = new File(target+ ".pdf");
        if (docFile.exists()) {
            if (!pdfFile.exists()) {
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
                try {
                    //连接
                    connection.connect();
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                    //转换
                    converter.convert(docFile, pdfFile);
                    //关闭连接
                    connection.disconnect();
                    pdfFile.mkdirs();
                    return pdfFile.getPath();
                } catch (java.net.ConnectException e) {
                    throw new java.net.ConnectException("openoffice转换异常:openoffice未启动!");
                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
                    throw new com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException("openoffice转换异常:读取文件失败!");
                }
            } else {
                return pdfFile.getPath();
            }
        } else {
            throw new Exception("openoffice转换异常:源文件未找到!");
        }
    }

    /**
     *  转为swf
     *  转换成功返回swf文件访问路径
     */
    public static String pdf2swf(String pdfFileSource) throws Exception {
        if (StringUtils.isEmpty(pdfFileSource)) {
            throw new Exception("swftools转换异常:源文件未空!");
        }
        File pdfFile = new File(pdfFileSource);
        String target = pdfFileSource.substring(0, pdfFileSource.lastIndexOf("."));
        File swfFile = new File(target+ ".swf");
        Runtime r = Runtime.getRuntime();
        if (pdfFile.exists()) {
            if (!swfFile.exists()) {
                if (1 == ENVIRONMENT) {// windows环境处理
                    try {
                        Process p = r.exec(swftoolsPath + "  \""+ pdfFile.getPath() + "\" -o \""+ swfFile.getPath() + "\" -T 9");
                        p.waitFor();
                        if (pdfFile.exists()){
                            //pdfFile.delete();
                        }
                    } catch (IOException e) {
                        throw new IOException("swftools转换异常:未找到swftools.exe");
                    } catch (InterruptedException e) {
                        throw new InterruptedIOException("swftools转换异常:转换失败!");
                    }
                } else if (2 == ENVIRONMENT) {// linux环境处理
                    try {
                        String command = "pdf2swf  " + pdfFile.getPath()+ " -o " + swfFile.getPath() + " -T 9";
                        Process p = r.exec(command);
                        p.waitFor();
                        if (pdfFile.exists()) {
    //                            pdfFile.delete();
                        }
                    } catch (InterruptedException e) {
                        throw new InterruptedIOException("swftools转换异常:转换失败!");
                    }
                }
            } else {
                return swfFile.getPath();
            }
        } else {
            throw new Exception("swftools转换异常:源文件未找到!");
        }
        return swfFile.getPath();
    }

    static String loadStream(InputStream in) throws IOException {
        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();
        while ((ptr = in.read()) != -1) {
            buffer.append((char) ptr);
        }
        return buffer.toString();
    }

    /**
     *返回文件路径
     * @param
     */
    public String getSwfPath(){
        if (this.swfFile.exists()){
            String tempString = swfFile.getPath();
            tempString = tempString.replaceAll("\\\\", "/");
            System.out.println("最后文件路径为"+tempString);
            return tempString;
        } else {
            return "文件不存在";
        }
    }

    /**
     * 设置输出路径
     *
     * @param outputPath
     */
    public void setOutputPath(String outputPath){
        this.outputPath = outputPath;
        if (!"".equals(outputPath) && null != outputPath) {
            String realName = fileName.substring(fileName.lastIndexOf("/"),
                    fileName.lastIndexOf("."));
            if (outputPath.charAt(outputPath.length()) == '/') {
                swfFile = new File(outputPath + realName + ".swf");
            } else {
                swfFile = new File(outputPath + realName + ".swf");
            }
        }
    }
}